#pragma warning(disable:4996)
#include <iostream>
#include <cstring>
#include <cassert>
using namespace std;

namespace ephemerals
{
	class string
	{
	public:
		typedef char* iterator;
		typedef const char* const_iterator;

		static size_t npos;

		iterator begin()
		{
			return _str;
		}
		iterator end()
		{
			return _str + _size;
		}
		const_iterator begin() const
		{
			return _str;
		}
		const_iterator end() const
		{
			return _str + _size;
		}

		void swap(string& s)
		{
			std::swap(_str, s._str);
			std::swap(_size, s._size);
			std::swap(_capacity, s._capacity);
		}

		string(const char* str = "")
			:_size(strlen(str))
		{
			_str = new char[_size + 1] {'\0'};
			_capacity = _size;
			strcpy(_str, str);
		}

		string(const string& s)
		{
			string tmp(s._str);
			swap(tmp);
		}

		string& operator=(string s)
		{
			swap(s);
			return *this;
		}

		~string()
		{
			if (_str)
			{
				delete[] _str;
			}
			_str = nullptr;
			_size = _capacity = 0;
		}

		const char* c_str() const
		{
			return _str;
		}

		void clear()
		{
			_str[0] = '\0';
			_size = 0;
		}

		size_t size() const
		{
			return _size;
		}

		size_t capacity() const
		{
			return _capacity;
		}

		void reserve(size_t n)
		{
			if (n > _capacity)
			{
				char* tmp = new char[n + 1] {'\0'};
				strcpy(tmp, _str);
				delete _str;
				_str = tmp;
				_capacity = n;
			}
		}

		char& operator[](size_t i)
		{
			assert(i < _size);
			return _str[i];
		}

		const char& operator[](size_t i) const
		{
			assert(i < _size);
			return _str[i];
		}

		void insert(size_t pos, char c)
		{
			assert(pos >= 0 && pos <= _size);
			if (_size == _capacity)
			{
				reserve(_capacity == 0 ? 4 : 2 * _capacity);
			}
			for (size_t i = _size; i > pos; i--)
			{
				_str[i] = _str[i - 1];
			}
			_str[pos] = c;
			_size++;
		}

		void insert(size_t pos, const char* str)
		{
			assert(pos >= 0 && pos <= _size);
			size_t len = strlen(str);
			if (len == 0) return;
			if (_size == _capacity)
			{
				size_t newCapacity = 2 * _capacity;
				if (newCapacity < _size + len)
				{
					newCapacity = _size + len;
				}
				reserve(newCapacity);
			}
			for (size_t i = _size; i >= pos; i--)
			{
				_str[i + len] = _str[i];
				if (i == 0) break;
			}
			for (size_t i = 0; i < len; i++)
			{
				_str[pos + i] = str[i];
			}
			_size += len;
		}
	private:
		char* _str;
		size_t _size;
		size_t _capacity;
	};

	ostream& operator<<(ostream& out, const string& s)
	{
		for (const auto& ch : s)
		{
			cout << ch;
		}
		return out;
	}

	size_t string::npos = -1;
}



int main()
{
	ephemerals::string s = "abcde";
	cout << s << endl;

	s.insert(5, "xxx");
	cout << s << endl;

	return 0;
}